﻿package mclight.layouts;
import mclight.Component;
import mclight.utils.Maths;

class _VBoxLayout extends LineLayout
{
	public function new() 
	{
		super();
		_gap = 4;
	}
	
	public override function arrange()
	{
		var gap = this.gap;
		var maxWidth = .0;
		var heightExpansion = 1.;
		if (autoSize)
		{
			for (component in _components)
			{
				if (component.width > maxWidth)
				{
					maxWidth = component.width;
				}
			}
		}
		else
		{
			var sumPortionHeightSize = height;
			var sumPortionHeight = .0;
			for (component in _components)
			{
				if (Math.isNaN(component.heightPortion))
				{
					sumPortionHeightSize -= component.height;
				}
				else
				{
					sumPortionHeight += component.heightPortion;
				}
				if (Math.isNaN(component.widthPortion) && component.width > maxWidth)
				{
					maxWidth = component.width;
				}
			}
			if (maxWidth > width)
			{
				width = maxWidth;
			}
			var numGaps = _components.length - 1;
			if (numGaps > 0)
			{
				sumPortionHeightSize -= numGaps * gap;
			}
			if (sumPortionHeightSize < 0)
			{
				sumPortionHeightSize = 0;
			}
			
			var k;
			if (sumPortionHeight * height < sumPortionHeightSize)
			{
				var pureHeight = height;
				if (numGaps > 0)
				{
					pureHeight -= numGaps * gap;
				}
				k = pureHeight / sumPortionHeightSize;
				var k1 = sumPortionHeight > 0 ? 1 / sumPortionHeight : 0;
				heightExpansion = k1 / k;
			}
			else
			{
				k = sumPortionHeight > 0 ? 1 / sumPortionHeight : 0;
			}
				
			for (component in _components)
			{
				if (!Math.isNaN(component.heightPortion))
				{
					var herald = component.heraldResize;
					herald.disableOn();
					component.height = sumPortionHeightSize * component.heightPortion * k;
					herald.disableOff();
				}
				if (!Math.isNaN(component.widthPortion))
				{
					var herald = component.heraldResize;
					herald.disableOn();
					component.width = width * component.widthPortion;
					herald.disableOff();
				}
			}
		}
		var offsetY = .0;
		for (component in _components)
		{
			component.x = (width - component.width) * component.alignX;
			if (Math.isNaN(component.heightPortion))
			{
				component.y = offsetY;
				offsetY += component.height + gap;
			}
			else
			{
				var spanHeight = component.height * heightExpansion;
				component.y = offsetY + (spanHeight - component.height) * component.alignY;
				offsetY += spanHeight + gap;
			}
		}
		width = Math.max(width, maxWidth);
		height = offsetY - gap;
		heraldArrange.dispatch(this);
	}
	
	public var gap(getGap, setGap):Float;
	var _gap:Float;
	function getGap()
	{
		return _gap;
	}
	function setGap(value)
	{
		return _gap = value;
	}
}